package com.neocean.archive.controller;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.neocean.archive.map.HonorMap;
import com.neocean.archive.model.HonorAttachmentModel;
import com.neocean.archive.model.HonorModel;
import com.neocean.archive.model.HonorPictureModel;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.Attachment;
import com.ruoyi.system.domain.Picture;
import com.ruoyi.system.service.IAttachmentService;
import com.ruoyi.system.service.IPictureService;
//import org.apache.commons.lang3.StringUtils;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.neocean.archive.domain.Honor;
import com.neocean.archive.service.IHonorService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

//import com.ruoyi.system.service.IPictureService;


import javax.annotation.Resource;

/**
 * 荣誉Controller
 * 
 * @author husb
 * @date 2021-11-16
 */
@RestController
@RequestMapping("/archive-honor/honor")
public class HonorController extends BaseController
{
    @Autowired
    private IHonorService honorService;

    @Autowired
    private IPictureService pictureService;

    @Autowired
    private IAttachmentService attachmentService;

    @Resource
    private HonorMap honorMap;

    /**
     * 查询荣誉列表
     */
    @PreAuthorize("@ss.hasPermi('archive-honor:honor:list')")
    @GetMapping("/list")
    public TableDataInfo list(Honor honor)
    {
        startPage();
        List<Honor> list = honorService.selectHonorList(honor);
        return getDataTable(list);
    }

    /**
     * 导出荣誉列表
     */
    @PreAuthorize("@ss.hasPermi('archive-honor:honor:export')")
    @Log(title = "荣誉", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Honor honor)
    {
        List<Honor> list = honorService.selectHonorList(honor);
        ExcelUtil<Honor> util = new ExcelUtil<Honor>(Honor.class);
        return util.exportExcel(list, "荣誉数据");
    }

    /**
     * 获取荣誉详细信息
     */
    @PreAuthorize("@ss.hasPermi('archive-honor:honor:query')")
    @GetMapping(value = "/{honorId}")
    public AjaxResult getInfo(@PathVariable("honorId") Long honorId)
    {
        Honor honor = honorService.selectHonorByHonorId(honorId);
        HonorModel model = honorMap.toHonorModel(honor);



        return AjaxResult.success(model);
    }

    /**
     * 新增荣誉
     */
    @PreAuthorize("@ss.hasPermi('archive-honor:honor:add')")
    @Log(title = "荣誉", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody HonorModel model)
    {
        // 1、用 map 工具 mapstruct， 将前端传过来的  model转换成 实体类
        Honor honor = honorMap.toHonor(model);
        // 2、手动修正实体类的属性值
        // 3、

        List<HonorPictureModel> pictures = model.getPictureList();
        if(pictures != null && pictures.size() > 0)
        {
            for (int i = 0; i < pictures.size(); i++) {
                HonorPictureModel pictureModel = pictures.get(i);
//                productService.insertProductPicture(new ProductPicture (null,
//                        product.getProductId(),
//                        pictureModel.getPictureId(),
//                        i + 1
//                ));
            }
        }


        int val = honorService.insertHonor(honor);
        //return toAjax(val);
        return AjaxResult.success( honor);
    }

    /**
     * 修改荣誉
     */
    @PreAuthorize("@ss.hasPermi('archive-honor:honor:edit')")
    @Log(title = "荣誉", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HonorModel model)
    {
        // return toAjax(honorService.updateHonor(honor));
        Honor honor = honorMap.toHonor(model);
//        if(model.isChangeCover()){
//            PictureModel coverModel = model.getCover();
//            if(coverModel != null){
//                Picture picture = systemObjectMapper.toPicture(coverModel);
//                picture.setCreatedBy(SecurityUtils.getUsername());
//                int i = pictureService.insertPicture(picture);
//                System.out.println("插入图片的自增Id： " + picture.getPictureId());
//                product.setCoverId(picture.getPictureId());
//            }
//        }
        int val = honorService.updateHonor(honor);
        return toAjax(val);
    }

    /**
     * 修改荣誉
     */
    @PreAuthorize("@ss.hasPermi('archive-honor:honor:edit')")
    @Log(title = "荣誉", businessType = BusinessType.UPDATE)
    @PutMapping("/edit-picture")
    public AjaxResult editPicture(@RequestBody HonorPictureModel model)
    {
        ArrayList<HonorPictureModel> pictures = new ArrayList<HonorPictureModel>();
        if(model.getHonorId() == 0) {
            return AjaxResult.success(pictures);
        }
        Honor honor = honorService.selectHonorByHonorId(model.getHonorId());

        if(!model.getVirtualPath().isEmpty()
                && honor.getPictures() != null
                && !"".equals(honor.getPictures())) {
            pictures  = JSON.parseObject(honor.getPictures(),
                    new TypeReference<ArrayList<HonorPictureModel>>(){});
        }
        if(StringUtils.isEmpty(honor.getPictures() )){
// isEmpty
        }
//        if(StringUtils.isNotBlank(honor.getPictures() )) {
//
//    }
//        Picture picture = new Picture();
//        picture.setMimeType(model.getMimeType());
//        picture.setOriginalFilename(model.getOriginalFilename());
//        picture.setPictureType(model.getPictureType());
//
//        picture.setVirtualPath(model.getVirtualPath());
        Picture picture = honorMap.toPicture(model);
        picture.setCreateBy(SecurityUtils.getUsername());
        picture.setCreateTime(DateUtils.getNowDate());

        int i = pictureService.insertPicture(picture);
        model.setPictureId(picture.getPictureId());
        model.setHonorPictureId(picture.getPictureId());

        model.setbNew(1);
        model.setHonorId(honor.getHonorId());
        model.setCreatedBy(SecurityUtils.getUsername());
        model.setCreatedAt(DateUtils.getNowDate());

//        HonorPictureModel honorPictureModel = new HonorPictureModel();
//        honorPictureModel.setHonorPictureId(picture.getPictureId());
//        honorPictureModel.setPictureId(picture.getPictureId());
//        honorPictureModel.setHonorId(honor.getHonorId());
//
//        honorPictureModel.setCreatedBy(SecurityUtils.getUsername());
//        honorPictureModel.setCreatedAt(DateUtils.getNowDate());
//        honorPictureModel.setPictureType(model.getPictureType());
//        honorPictureModel.setbNew(1);
//
//        honorPictureModel.setMimeType(model.getMimeType());
//        honorPictureModel.setOriginalFilename(model.getOriginalFilename());
//        honorPictureModel.setPictureType(model.getPictureType());
//        honorPictureModel.setVirtualPath(model.getVirtualPath());

        pictures.add(model);
        honor.setPictures( JSON.toJSONString(pictures));
        int val = honorService.updateHonor(honor);
        // return toAjax(val);
        return AjaxResult.success( honor.getPictures());

        // return toAjax(honorService.updateHonor(honor));
        // Honor honor = honorMap.toHonor(model);
//        if(model.isChangeCover()){
//            PictureModel coverModel = model.getCover();
//            if(coverModel != null){
//                Picture picture = systemObjectMapper.toPicture(coverModel);
//                picture.setCreatedBy(SecurityUtils.getUsername());
//                int i = pictureService.insertPicture(picture);
//                System.out.println("插入图片的自增Id： " + picture.getPictureId());
//                product.setCoverId(picture.getPictureId());
//            }
//        }
        // return AjaxResult.error("图片路径不正确");
    }

    /**
     * 修改荣誉
     */
    @PreAuthorize("@ss.hasPermi('archive-honor:honor:edit')")
    @Log(title = "荣誉", businessType = BusinessType.UPDATE)
    @PutMapping("/edit-attachment")
    public AjaxResult editAttachment(@RequestBody HonorAttachmentModel model)
    {
        ArrayList<HonorAttachmentModel> attachments = new ArrayList<HonorAttachmentModel>();
        if(model.getHonorId() == 0) {
            return AjaxResult.success(attachments);
        }
        Honor honor = honorService.selectHonorByHonorId(model.getHonorId());

        if(!model.getVirtualPath().isEmpty()
                && !StringUtils.isEmpty(honor.getAttachments() )) {
            attachments  = JSON.parseObject(honor.getAttachments(),
                    new TypeReference<ArrayList<HonorAttachmentModel>>(){});
        }
        if(StringUtils.isEmpty(honor.getAttachments() )){
// isEmpty
        }
//        if(StringUtils.isNotBlank(honor.getPictures() )) {
//
//    }
//        Picture picture = new Picture();
//        picture.setMimeType(model.getMimeType());
//        picture.setOriginalFilename(model.getOriginalFilename());
//        picture.setPictureType(model.getPictureType());
//
//        picture.setVirtualPath(model.getVirtualPath());
        Attachment attachment = honorMap.toAttachment(model);
        attachment.setCreateBy(SecurityUtils.getUsername());
        attachment.setCreateTime(DateUtils.getNowDate());

        int i = attachmentService.insertAttachment(attachment);
        model.setAttachmentId(attachment.getAttachmentId());
        model.setHonorAttachmentId(attachment.getAttachmentId());

        model.setbNew(1);
        model.setHonorId(honor.getHonorId());
        model.setCreateBy(SecurityUtils.getUsername());
        model.setCreateTime(DateUtils.getNowDate());

//        HonorPictureModel honorPictureModel = new HonorPictureModel();
//        honorPictureModel.setHonorPictureId(picture.getPictureId());
//        honorPictureModel.setPictureId(picture.getPictureId());
//        honorPictureModel.setHonorId(honor.getHonorId());
//
//        honorPictureModel.setCreatedBy(SecurityUtils.getUsername());
//        honorPictureModel.setCreatedAt(DateUtils.getNowDate());
//        honorPictureModel.setPictureType(model.getPictureType());
//        honorPictureModel.setbNew(1);
//
//        honorPictureModel.setMimeType(model.getMimeType());
//        honorPictureModel.setOriginalFilename(model.getOriginalFilename());
//        honorPictureModel.setPictureType(model.getPictureType());
//        honorPictureModel.setVirtualPath(model.getVirtualPath());

        attachments.add(model);
        honor.setAttachments( JSON.toJSONString(attachments));
        int val = honorService.updateHonor(honor);
//        return toAjax(val);
        return AjaxResult.success( honor.getAttachments());

        // return toAjax(honorService.updateHonor(honor));
        // Honor honor = honorMap.toHonor(model);
//        if(model.isChangeCover()){
//            PictureModel coverModel = model.getCover();
//            if(coverModel != null){
//                Picture picture = systemObjectMapper.toPicture(coverModel);
//                picture.setCreatedBy(SecurityUtils.getUsername());
//                int i = pictureService.insertPicture(picture);
//                System.out.println("插入图片的自增Id： " + picture.getPictureId());
//                product.setCoverId(picture.getPictureId());
//            }
//        }
        // return AjaxResult.error("图片路径不正确");
    }

    /**
     * 删除荣誉
     */
    @PreAuthorize("@ss.hasPermi('archive-honor:honor:remove')")
    @Log(title = "荣誉", businessType = BusinessType.DELETE)
	@DeleteMapping("/{honorIds}")
    public AjaxResult remove(@PathVariable Long[] honorIds)
    {
        return toAjax(honorService.deleteHonorByHonorIds(honorIds));
    }
    
    // region

    @PreAuthorize("@ss.hasPermi('catalog:product:list')")
    @GetMapping("picture")
    public AjaxResult getHonorPictures(long honorId)
    {
        Honor honor = honorService.selectHonorByHonorId(honorId);
        // List<ProductPicture> productPictures = productService.getProductPictureList(productId);
        List<HonorPictureModel> model = new ArrayList<>();
        if(honor == null || honor.getPictures().isEmpty()) {
            return AjaxResult.success(model);
        }
        ArrayList<HonorPictureModel> pictures  = JSON.parseObject(honor.getPictures(),
                new TypeReference<ArrayList<HonorPictureModel>>(){});
        // List<Game> gameList = JSONObject.parseArray(gameListStr, Game.class);
//        AjaxResult ajax = AjaxResult.success(model);
        return AjaxResult.success(honor.getPictures());
    }
    
    // endregion
}
